<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\services\common;

use think\cache\TagSet;
use think\facade\Cache;
use think\facade\Config;
use Throwable;

class CacheService
{
    protected static int $expire; // 过期时间

    /**
     * 写入缓存
     * @param string $name 缓存名称
     * @param mixed $value 缓存值
     * @param int $expire 缓存时间，为0读取系统缓存时间
     * @param string $tag
     * @return bool
     */
    public static function set(string $name, mixed $value, int $expire = 0, string $tag = 'kitego'): bool
    {
        try {
            return Cache::tag($tag)->set($name, $value, $expire);
        } catch (Throwable $e) {
            return false;
        }
    }

    /**
     * 如果不存在则写入缓存
     */
    public static function remember(string $name, $default = '', int $expire = 0, string $tag = 'kitego')
    {
        try {
            return Cache::tag($tag)->remember($name, $default, $expire);
        } catch (Throwable $e) {
            try {
                if (is_callable($default)) {
                    return $default();
                } else {
                    return $default;
                }
            } catch (Throwable $e) {
                return null;
            }
        }
    }

    /**
     * 读取缓存
     * @param string $name
     * @param mixed $default
     * @return mixed
     */
    public static function get(string $name, mixed $default = ''): mixed
    {
        return Cache::get($name) ?? $default;
    }

    /**
     * 删除缓存
     * @param string $name
     * @return bool
     */
    public static function delete(string $name): bool
    {
        return Cache::delete($name);
    }

    /**
     * 清空缓存池
     * @param string $tag
     * @return bool
     */
    public static function clear(string $tag = 'kitego'): bool
    {
        return Cache::tag($tag)->clear();
    }

    /**
     * 检查缓存是否存在
     * @param string $key
     * @return bool
     */
    public static function has(string $key): bool
    {
        try {
            return Cache::has($key);
        } catch (Throwable $e) {
            return false;
        }
    }

    /**
     * 指定缓存类型
     * @param string $type
     * @param string $tag
     * @return TagSet
     */
    public static function store(string $type = 'file', string $tag = 'kitego'): TagSet
    {
        return Cache::store($type)->tag($tag);
    }

    /**
     * 检查锁
     * @param string $key
     * @param int $timeout
     * @return bool
     */
    public static function setMutex(string $key, int $timeout = 10): bool
    {
        $curTime = time();
        $readMutexKey = "redis:mutex:{$key}";
        $mutexRes = Cache::store('redis')->handler()->setnx($readMutexKey, $curTime + $timeout);
        if ($mutexRes) {
            return true;
        }

        // 就算意外退出，下次进来也会检查key，防止死锁
        $time = Cache::store('redis')->handler()->get($readMutexKey);
        if ($curTime > $time) {
            Cache::store('redis')->handler()->del($readMutexKey);

            return Cache::store('redis')->handler()->setnx($readMutexKey, $curTime + $timeout);
        }

        return false;
    }

    /**
     * 删除锁
     * @param string $key
     */
    public static function delMutex(string $key): void
    {
        $readMutexKey = "redis:mutex:{$key}";

        Cache::store('redis')->handler()->del($readMutexKey);
    }

    /**
     * 数据库锁
     * @param $key
     * @param $fn
     * @param int $ex
     * @return mixed
     */
    public static function lock($key, $fn, int $ex = 6): mixed
    {
        if (Config::get('cache.default') == 'file') {
            return $fn();
        }

        return LockService::exec($key, $fn, $ex);
    }
}
